package com.njtoyo.taxi.admin.logic.open;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.njtoyo.taxi.admin.library.taxi_service.SimpleCallTaxiService;
import com.njtoyo.taxi.admin.mapper.master.entity.OnCallBacklog;
import com.njtoyo.taxi.admin.mapper.master.mapper.OnCallBacklogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class OnCallBacklogLogic {
    
    @Autowired
    private OnCallBacklogMapper onCallBacklogMapper;

    @Autowired
    private SimpleCallTaxiService simpleCallTaxiService;

    @Async
    public void sendOnCallBacklog(Long id) {
        log.info("正在发送电召单 on-call {}", id);
        OnCallBacklog backlog = onCallBacklogMapper.selectById(id);
        if (Objects.isNull(backlog)) {
            log.info("电召单不存在");
            return;
        }
        if (Objects.nonNull(backlog.getSimpleCallId())) {
            log.info("该呼叫已发送");
            return;
        }
        log.info("正在发送电召单");
        Long callId = simpleCallTaxiService.sendOnCall(id);
        if (Objects.nonNull(callId)) {
            new LambdaUpdateChainWrapper<>(onCallBacklogMapper)
                    .eq(OnCallBacklog::getId, id)
                    .set(OnCallBacklog::getSimpleCallId, callId)
                    .set(OnCallBacklog::getUpdatedAt, new Date())
                    .update();
        }
    }

    @Async
    public void sendCallback(String url, Map body) {
        log.info("callback request {}", body);
        String res = HttpRequest.post(url)
                .header("app", "hitaxi")
                .body(JSONUtil.toJsonStr(body))
                .execute().body();
        log.info("callback response {}", res);
    }
}
